package org.redis;

import java.net.Socket;
import java.util.HashSet;
import java.util.Set;

import org.junit.Test;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisSentinelPool;

public class RedisSentinelTest {

	// 通过不同长度的key，测试数据是否均匀分布在三个redis实例
	@Test
	public void proxyTest() {
		Jedis jedis = null;
		String response = null;

		jedis = new Jedis("127.0.0.1", 19000);
		response = jedis.set("a", "tony_a");
		jedis.close();
		System.out.println("返回结果:" + response);

		jedis = new Jedis("127.0.0.1", 19000);
		response = jedis.set("ab", "tony_ab");
		jedis.close();
		System.out.println("返回结果:" + response);

		jedis = new Jedis("127.0.0.1", 19000);
		response = jedis.set("abc", "tony_abc");
		jedis.close();
		System.out.println("返回结果:" + response);

		jedis = new Jedis("127.0.0.1", 19000);
		response = jedis.set("abcd", "tony_abcd");
		jedis.close();
		System.out.println("返回结果:" + response);

	}

	// 哨兵机制测试
	@Test
	public static void sentinelTest() {
		// SENTINEL get-master-addr-by-name master
		Set<String> sentinels = new HashSet<String>();
		// 这里添加哨兵服务器
		sentinels.add("localhost:26380");

		JedisSentinelPool jedisSentinelPool = new JedisSentinelPool("mymaster", sentinels);
		Jedis jedis = jedisSentinelPool.getResource();

		jedis.set("hello_sentinel_3", "tony_sentinel_3");
	}

	// 通过这个socket客户端发出请求
	// 获取sentinel的响应内容
	@Test
	public void sentinelClientTest() throws Exception {
		// SENTINEL get-master-addr-by-name master
		Socket socket = new Socket("127.0.0.1", 26380);

		socket.getOutputStream().write(("*3\r\n" + "$8\r\n" + "SENTINEL\r\n" + "$23\r\n" + "get-master-addr-by-name\r\n"
				+ "$6\r\n" + "master\r\n").getBytes());

		byte[] response = new byte[1024];
		socket.getInputStream().read(response);

		System.out.println(new String(response));
	}
}
